// pages/login/login.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    userAvataUrl: '',
    tips: '获得你的公开信息(昵称,头像)',
    opentype:'getUserInfo',
    loginBtnStr:'授权登陆',
    userCode:'',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow: function(){
    wx.hideHomeButton();
       
  },
  bindGetUserInfo(res) {
    console.log(res);
    let that = this;
    // 登录
    wx.login({
      success: resdata => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.setData({
          userCode:resdata.code
        })
        app.globalData.userCode = resdata.code;
        if (res.detail.userInfo) {
          //用户按了允许授权按钮
          // 获取到用户的信息了
          let userInfo = res.detail.userInfo;
          app.globalData.userInfo = userInfo;
          let data = {
            avatar: userInfo.avatarUrl,
            city: userInfo.city,
            code: that.data.userCode,
            gender: userInfo.gender,
            nickName: userInfo.nickName
          }
          app.request.postForm('hgz/open/weixin/login',data)
          .then(res =>{
            console.log(res);
            if (res.status == true) {
              let token = res.data.token;
              wx.setStorageSync("token", res.data.userId+"_"+token);
              app.globalData.token = token;
              that.setData({
                opentype: 'getPhoneNumber',
                tips: '获得你的公开信息(手机号)',
                loginBtnStr: '获取手机号'
              })
            }else{
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 2000
              });
            }
          })
        }  
      }
    })
  },
  getAgreement(res){
    wx.navigateTo({
      url: '/pages/useragreement/agreement',
    })
  },
  bindGetPhone(res) {
    console.log(res);
    console.log(res.detail.errMsg == "getPhoneNumber:ok");
    let that = this;
    var form  =  {
      encryptedData: res.detail.encryptedData,
      iv: res.detail.iv,
      token: wx.getStorageSync("token")
    }
    app.request.postForm('hgz/open/weixin/bindMobile',form)
    .then(res =>{
      console.log(res);
      app.globalData.isLogin = true;
      wx.reLaunch({
        url: '../home/home',
      })
    })
  }
  
})